<template>
  <div class="company-manage-view">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="search-bar">
      <el-form-item>
        <el-input v-model="searchForm.shortName" placeholder="公司简称" clearable />
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.fullName" placeholder="公司全称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border stripe style="width: 100%" class="company-table" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="48" />
      <el-table-column prop="shortName" label="公司简称" width="120">
        <template #default="scope">
          <el-tag
            v-if="scope.row.shortName === '运输企业'"
            type="danger"
            effect="plain"
            class="company-tag company-tag-danger"
          >运输企业</el-tag>
          <el-tag
            v-else-if="scope.row.shortName === '配送中心'"
            type="warning"
            effect="plain"
            class="company-tag company-tag-warning"
          >配送中心</el-tag>
          <el-tag
            v-else-if="scope.row.shortName === '物流公司'"
            type="success"
            effect="plain"
            class="company-tag company-tag-success"
          >物流公司</el-tag>
          <span v-else>{{ scope.row.shortName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inquiryPhone" label="查询电话" width="140" />
      <el-table-column prop="complaintPhone" label="投诉电话" width="140" />
      <el-table-column prop="fullName" label="公司全称" width="180" />
      <el-table-column prop="address" label="详细地址" width="200" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="editRow(scope.row, scope.$index)">编辑</el-button>
          <el-button type="text" style="color: #ff4d4f" @click="deleteRow(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-bar">
      <span>共 {{ total }} 条</span>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 弹窗表单 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="公司简称" prop="shortName">
          <el-select v-model="form.shortName" placeholder="请选择公司简称">
            <el-option label="物流公司" value="物流公司" />
            <el-option label="运输企业" value="运输企业" />
            <el-option label="配送中心" value="配送中心" />
          </el-select>
        </el-form-item>
        <el-form-item label="查询电话" prop="inquiryPhone">
          <el-input v-model="form.inquiryPhone" />
        </el-form-item>
        <el-form-item label="投诉电话" prop="complaintPhone">
          <el-input v-model="form.complaintPhone" />
        </el-form-item>
        <el-form-item label="公司全称" prop="fullName">
          <el-input v-model="form.fullName" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dataAPI } from '@/http/leancloud'

const searchForm = ref({ shortName: '', fullName: '' })
const tableData = ref<any[]>([])
const total = ref(0)
const page = ref({ current: 1, size: 10 })
const dialogVisible = ref(false)
const dialogTitle = ref('新增公司')
const formRef = ref()
const form = ref<any>({
  shortName: '',
  inquiryPhone: '',
  complaintPhone: '',
  fullName: '',
  address: ''
})
const rules = {
  shortName: [{ required: true, message: '请输入公司简称', trigger: 'blur' }],
  inquiryPhone: [{ required: true, message: '请输入查询电话', trigger: 'blur' }],
  fullName: [{ required: true, message: '请输入公司全称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}
const editIndex = ref(-1)
const multipleSelection = ref<any[]>([])

const fetchCompanies = async () => {
  const where: any = {}
  if (searchForm.value.shortName) where.shortName = { "$regex": searchForm.value.shortName }
  if (searchForm.value.fullName) where.fullName = { "$regex": searchForm.value.fullName }
  // 先查總數
  const allResults = await dataAPI.query('Company', where)
  total.value = allResults.length
  // 分頁查詢
  const limit = page.value.size
  const skip = (page.value.current - 1) * page.value.size
  const results = await dataAPI.query('Company', where, undefined, limit, skip)
  tableData.value = results.map((item: any) => ({
    objectId: item.objectId,
    shortName: item.shortName,
    inquiryPhone: item.inquiryPhone,
    complaintPhone: item.complaintPhone,
    fullName: item.fullName,
    address: item.address,
    createTime: item.createdAt ? new Date(item.createdAt).toLocaleString() : ''
  }))
}
const handleSearch = () => {
  fetchCompanies()
}
const handleReset = () => {
  searchForm.value = { shortName: '', fullName: '' }
  fetchCompanies()
}
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const handleSizeChange = (size: number) => {
  page.value.size = size
  fetchCompanies()
}
const handlePageChange = (current: number) => {
  page.value.current = current
  fetchCompanies()
}
const handleAdd = () => {
  dialogTitle.value = '新增公司'
  form.value = {
    shortName: '',
    inquiryPhone: '',
    complaintPhone: '',
    fullName: '',
    address: ''
  }
  editIndex.value = -1
  dialogVisible.value = true
}
const editRow = (row: any, index: number) => {
  dialogTitle.value = '编辑公司'
  form.value = { ...row }
  editIndex.value = index
  dialogVisible.value = true
}
const handleDialogConfirm = async () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const data = {
        shortName: form.value.shortName,
        inquiryPhone: form.value.inquiryPhone,
        complaintPhone: form.value.complaintPhone,
        fullName: form.value.fullName,
        address: form.value.address
      }
      if (editIndex.value === -1) {
        await dataAPI.save('Company', data)
        ElMessage.success('新增成功')
      } else {
        await dataAPI.save('Company', { ...data, objectId: form.value.objectId })
        ElMessage.success('修改成功')
      }
      dialogVisible.value = false
      fetchCompanies()
    }
  })
}
const deleteRow = (row: any, index: number) => {
  ElMessageBox.confirm(
    `确认删除公司 "${row.shortName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await dataAPI.delete('Company', row.objectId)
    ElMessage.success('删除成功')
    fetchCompanies()
  }).catch(() => {})
}
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的公司！')
    return
  }
  ElMessageBox.confirm(
    `确认删除选中的 ${multipleSelection.value.length} 个公司吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    for (const item of multipleSelection.value) {
      await dataAPI.delete('Company', item.objectId)
    }
    ElMessage.success('删除成功')
    fetchCompanies()
    multipleSelection.value = []
  }).catch(() => {})
}
onMounted(() => {
  fetchCompanies()
})
</script>

<style scoped>
.company-manage-view {
  padding: 24px 16px 0 16px;
  background: #f4f6fa;
  min-height: 100vh;
}
.search-bar,
.toolbar,
.company-table,
.pagination-bar {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  margin-bottom: 18px;
  padding: 18px 24px;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 14px;
  padding-bottom: 10px;
}
.search-bar .el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}
.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-bottom: 14px;
}
.toolbar .el-button {
  border-radius: 6px;
  font-weight: 500;
  letter-spacing: 1px;
}
.company-table {
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
  padding: 0;
}
.company-table .el-table__header th {
  background: #f4f6fa;
  color: #222;
  font-weight: 600;
  font-size: 15px;
  height: 48px;
}
.company-table .el-table__row {
  font-size: 14px;
  height: 44px;
}
.company-table .el-button[type="text"] {
  padding: 0 8px;
  font-size: 15px;
  border-radius: 4px;
  transition: background 0.2s;
}
.company-table .el-button[type="text"]:hover {
  background: #f0f7ff;
}
.company-table .el-button[type="text"]:nth-child(2) {
  color: #ff4d4f;
}
.pagination-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 0;
  padding: 12px 24px;
  box-shadow: none;
}
.pagination-bar .el-pagination {
  margin-left: 8px;
}
.el-dialog__body {
  padding-top: 18px !important;
  padding-bottom: 8px !important;
}
.el-dialog__footer {
  padding-bottom: 18px !important;
}
.el-dialog .el-form-item__label {
  font-weight: 500;
  color: #333;
}
.el-dialog .el-input,
.el-dialog .el-select {
  width: 260px;
}
.el-dialog .el-button {
  border-radius: 6px;
  min-width: 80px;
}
.company-tag {
  font-size: 16px;
  padding: 0 18px;
  height: 36px;
  line-height: 34px;
  border-radius: 10px;
  font-weight: 500;
  margin: 0 auto;
  display: inline-block;
}
.company-tag-danger {
  color: #e74c3c;
  background: #ffeaea;
  border-color: #ffd6d6;
}
.company-tag-warning {
  color: #e67e22;
  background: #fff7e6;
  border-color: #ffe6b3;
}
.company-tag-success {
  color: #27ae60;
  background: #eaffea;
  border-color: #b7f5c7;
}
</style> 